<template>
  <div class="container">
    <el-card class="el-card-container" :body-style="{ padding: '0px' }">
      <h2 class="title">{{ params ? '试题修改' : '试题录入' }}</h2>
      <el-form label-width="100px" :model="formData" :rules="rules" ref="formDataRef">
        <el-form-item label="学科:" style="width: 500px" prop="subjectID">
          <el-select
            clearable
            v-model="formData.subjectID"
            placeholder="请选择"
            style="width: 100%"
            @change="subjectSelectChange"
          >
            <el-option
              v-for="item in subjectsList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录:" style="width: 500px" prop="catalogID">
          <el-select placeholder="请选择" style="width: 100%" v-model="formData.catalogID" clearable>
            <el-option v-for="item in directorysList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业:" style="width: 500px" prop="enterpriseID">
          <el-select placeholder="请选择" style="width: 100%" v-model="formData.enterpriseID" clearable>
            <el-option v-for="item in companyList" :key="item.id" :label="item.company" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市:" style="width: 500px" prop="province">
          <el-select
            clearable
            placeholder="请选择"
            class="citySelect"
            style="width: 49.5%"
            v-model="formData.province"
            @change="provinceChange"
          >
            <el-option v-for="(item, index) in provincesListFn" :key="index" :label="item" :value="item"> </el-option>
          </el-select>
          <el-select clearable placeholder="请选择" style="width: 49.5%" v-model="formData.city">
            <el-option v-for="(item, index) in cityList" :key="index" :label="item" :value="item"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方向:" style="width: 500px" prop="direction">
          <el-select clearable placeholder="请选择" style="width: 100%" v-model="formData.direction">
            <el-option v-for="(item, index) in directionList" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型:">
          <el-radio-group v-model="formData.questionType">
            <el-radio v-for="item in questionTypeArr" :key="item.value" :label="String(item.value)">{{
              item.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度:">
          <el-radio-group v-model="formData.difficulty">
            <el-radio v-for="item in difficultyArr" :key="item.value" :label="String(item.value)">{{
              item.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干:" prop="question">
          <quill-editor
            :options="editorOption"
            v-model="formData.question"
            ref="myQuillEditor"
            class="editor"
            @blur="questionBlur"
          >
          </quill-editor>
        </el-form-item>
        <!-- 动态增减表单项 -->
        <questionsOptions
          ref="questionComponent"
          :questionType="formData.questionType"
          v-if="formData.questionType !== '3'"
        ></questionsOptions>
        <el-form-item label="解析视频:" style="width: 500px">
          <el-input v-model="formData.videoURL"></el-input>
        </el-form-item>
        <el-form-item label="答案解析:" prop="answer">
          <quill-editor
            :options="editorOption"
            v-model="formData.answer"
            ref="myQuillEditor"
            class="editor"
            @blur="answerBlur"
          >
          </quill-editor>
        </el-form-item>
        <el-form-item label="题目备注:" style="width: 500px">
          <el-input type="textarea" v-model="formData.remarks"></el-input>
        </el-form-item>
        <el-form-item label="试题标签:" style="width: 500px">
          <el-select v-model="formData.tags" placeholder="请选择试题标签" multiple style="width: 100%">
            <el-option
              v-for="item in tagsList"
              :key="item.value"
              :label="item.label"
              :value="String(item.label)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button v-if="!params" type="primary" size="small" @click="submitQuestions">确认提交</el-button>
          <el-button v-else type="success" size="small" @click="submitQuestions">确认修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { simple as subjectsSimpleAPI } from '@/api/hmmm/subjects.js'
import { simple as directorysSimpleAPI } from '@/api/hmmm/directorys.js'
import { list as companyListAPI } from '@/api/hmmm/companys.js'
import { provinces as provincesListFn, citys } from '@/api/hmmm/citys.js'
import { simple as tagsSimpleAPI } from '@/api/hmmm/tags.js'
import {
  direction as directionList,
  difficulty as difficultyArr,
  questionType as questionTypeArr
} from '@/api/hmmm/constants.js'
import questionsOptions from '../components/questions-options.vue'
import { add, detail, update } from '@/api/hmmm/questions.js'
export default {
  data () {
    return {
      // 表单数据
      formData: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        direction: '', // 方向
        province: '', // 城市
        city: '', // 地区
        difficulty: '1', // 难度
        question: '', // 题干
        questionType: '1', // 题型
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 试题标签
      },
      // 验证规则
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'change' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'change' }],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'change' }],
        province: [{ required: true, message: '请选择城市和地区', trigger: 'change' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'change' }],
        question: [{ required: true, message: '请输入题干' }],
        answer: [{ required: true, message: '请输入答案解析' }]
      },
      subjectsList: [], // 学科列表
      directorysList: [], // 目录列表
      companyList: [], // 企业列表
      directionList: directionList, // 方向列表
      provincesListFn: provincesListFn(), // 所有城市
      cityList: [], // 地区列表
      difficultyArr: difficultyArr, // 难度数组
      questionTypeArr: questionTypeArr, // 题型数组
      tagsList: [], // 试题标签数组
      editorOption: {
        // 富文本编辑器配置
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            ['blockquote', 'code-block'], // 引用，代码块
            // [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小
            // [{ script: 'sub' }, { script: 'super' }], // 上下标
            // [{ indent: '-1' }, { indent: '+1' }], // 缩进
            // [{ direction: 'rtl' }], // 文本方向
            // [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
            // [{ header: [1, 2, 3, 4, 5, 6, false] }], // 几级标题
            // [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
            // [{ font: [] }], // 字体
            // [{ align: [] }], // 对齐方式
            // ['clean'], // 清除字体样式
            // ['image', 'video'] // 上传图片、上传视频
            ['image'], // 上传图片
            ['link'] // 链接
          ]
        }
      },
      // params 查询参数
      params: null
    }
  },
  components: {
    questionsOptions // 选项组件
  },
  created () {
    this.init() // 调用-初始化
    // console.log(this.provincesList)
    if (this.params) this.paramsData() // 判断参数 调用
  },
  watch: {
    $route: {
      // 监测路由对象的改变(路由页面跳转这里就触发)
      handler: function (route) {
        this.params = route.query && route.query.id
      },
      immediate: true
    }
  },
  methods: {
    // 判断参数获取数据
    async paramsData () {
      const { data } = await detail({ id: this.params })
      this.formData = data
      console.log(data.options)
      this.$refs.questionComponent.options.questions = [
        { code: String.fromCharCode(this.serialNumber++), title: '', img: '', isRight: false },
        ...data.options
      ]
      console.log(this.$refs.questionComponent.options.questions)
    },
    // 初始化(学科/企业)
    async init () {
      const { data: subjectsSimpleData } = await subjectsSimpleAPI()
      const {
        data: { items: companyListData }
      } = await companyListAPI()
      this.subjectsList = subjectsSimpleData
      this.companyList = companyListData
    },
    // 目录简单列表
    async getDirectorysSimpleList () {
      const { data: directorysSimpleData } = await directorysSimpleAPI({ subjectID: Number(this.formData.subjectID) })
      this.directorysList = directorysSimpleData
    },
    // 试题标签列表
    async getTagsSimpleList () {
      const { data } = await tagsSimpleAPI({ subjectID: Number(this.formData.subjectID) })
      this.tagsList = data
    },
    // 学科触发变化
    subjectSelectChange () {
      this.formData.catalogID = '' // 清空目录选中项
      this.getDirectorysSimpleList() // 获取目录
      this.formData.tags = '' // 清空试题标签选中项
      this.getTagsSimpleList() // 获取试题标签列表
    },
    // 城市触发变化
    provinceChange () {
      this.formData.city = ''
      this.cityList = citys(this.formData.province)
    },
    // 提交
    submitQuestions () {
      this.$refs.formDataRef.validate(async valid => {
        if (!valid) return
        let options
        // 判断 如果不是简答题 获取数据
        if (this.formData.questionType !== '3') {
          options = this.$refs.questionComponent.options.questions.slice(1)
        } else {
          // 如果是简答题 传递空
          options = []
        }
        const tags = this.formData.tags.toString()
        if (this.params) {
          console.log('我是修改')
          try {
            await update({ ...this.formData, tags: tags, options })
            this.$message.success('试题修改成功!')
          } catch (error) {}
        } else {
          try {
            await add({
              ...this.formData,
              tags: tags,
              options
            })
            this.$message.success('试题录入成功!')
          } catch (error) {}
        }
        this.$router.push('/questions/list')
      })
    },
    // 题干校验  自定义blur 失去焦点触发
    questionBlur () {
      this.$refs.formDataRef.validateField('question')
    },
    // 答案解析校验 自定义blur 失去焦点触发
    answerBlur () {
      this.$refs.formDataRef.validateField('answer')
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  .el-card {
    margin: 20px;
    padding: 0 !important;
  }
  .el-form {
    margin: 20px;
  }
  .title {
    margin: 0;
    font-size: 16px;
    font-weight: normal;
    color: #303133;
    padding: 18px 20px;
    border-bottom: 1px solid #ebeef5;
  }
  .citySelect {
    margin-right: 1%;
  }
}
::v-deep .quill-editor {
  .ql-container {
    height: 200px;
  }
  .ql-toolbar {
    padding: 0 8px;
  }
  .ql-toolbar.ql-snow .ql-formats {
    margin-right: 0;
  }
}
</style>
